import { clearUserLocalStorage } from "../../../../utils/util";

const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        delivery_man_id: 0,
        delivery_man_name: '',
        history: [],
        min_date: new Date(2010, 0, 1),
        max_date: new Date(),
        show_select: false,
        view_public: 0,
        show_search_bar: true,
        search_word: '',
        show_calendar: true, //显示日历
        date: new Date(),
        currentMonth: new Date().getMonth(), // 当前月份
        currentYear: new Date().getFullYear(), // 当前年份
        today: new Date().getTime(), // 当前日期
        nextMonthDisabled: true,
        formatter(day) {
            return day;
        },
    },

    async onLoad(options) {
        let now = (new Date().getTime()) / 1000;
        let expiration_time = app.session.expiration_time ?? 0
        if (now > expiration_time) {
            console.log('已过登录有效期!')
            app.session = {}
            clearUserLocalStorage()
            wx.reLaunch({
                url: '/pages/selectID/selectID',
            })
        }

        console.log('session:', app.session)

        let access_token = app.session.access_token
        let delivery_man = app.session.user
        let current_delivery_man_id = wx.getStorageSync('current_delivery_man_id') || 0
        let delivery_man_list = app.session.delivery_man_list
        let delivery_district_list = app.session.delivery_district_list

        const today = new Date();
        const min_date = new Date(today.getFullYear(), today.getMonth(), 1);
        min_date.setHours(0, 0, 0, 0);

        this.setData({
            access_token,
            delivery_man,
            current_delivery_man_id,
            min_date: min_date.getTime(),
            max_date: today.getTime(),
            delivery_man_list: delivery_man_list,
            delivery_district_list: delivery_district_list,
            today: new Date().getTime(),
        });

        this.updateNextMonthDisabled();

        await this.getDeliveryStatistics();
    },

    onReady() { },
    onShow() { },
    onHide() { },
    onUnload() { },

    onPullDownRefresh() {
        wx.stopPullDownRefresh();
    },

    onReachBottom() { },

    onShareAppMessage() { },

    updateNextMonthDisabled() {
        let today = new Date();
        this.setData({
            nextMonthDisabled: (this.data.currentYear === today.getFullYear() && this.data.currentMonth === today.getMonth())
        });
    },

    prevMonth() {
        let newMonth = this.data.currentMonth - 1;
        let newYear = this.data.currentYear;
        if (newMonth < 0) {
            newMonth = 11;
            newYear--;
        }
        this.updateCalendar(newYear, newMonth);
    },

    nextMonth() {
        let newMonth = this.data.currentMonth + 1;
        let newYear = this.data.currentYear;
        if (newMonth > 11) {
            newMonth = 0;
            newYear++;
        }
        this.updateCalendar(newYear, newMonth);
    },

    updateCalendar(year, month) {
        let min_date = new Date(year, month, 1).getTime();
        let max_date = new Date(year, month + 1, 0, 23, 59, 59).getTime();
        this.setData({
            currentMonth: month,
            currentYear: year,
            min_date: min_date,
            max_date: max_date,
        });
        this.updateNextMonthDisabled();
        this.getDeliveryStatistics(); // 重新获取数据
    },
    onConfirm(event) {
        const selectedDate = event.detail; // 获取选中的日期
        console.log('选中的日期:', selectedDate);
        wx.setStorageSync('viewDeliveryDate', selectedDate)
        wx.navigateTo({
            url: '/templates/deliver/pages/delivered/delivered',
            /*success: (res) => {
                res.eventChannel.emit('selectedDate', { date: selectedDate });
            }
            */
        });
    },

    on_dropdown_change(e) {
        const current_delivery_man_id = e.detail;
        let current_delivery_name = '未知'
        let current_delivery_district_id = 0

        const delivery_man = this.data.delivery_man_list.find(d => d.value === current_delivery_man_id);
        if (delivery_man) {

            current_delivery_name = delivery_man.text;
            current_delivery_district_id = delivery_man.delivery_district_id

            console.log('----', current_delivery_district_id)
        }

        this.setData({
            current_delivery_man_id: current_delivery_man_id,
            current_delivery_name: current_delivery_name,
            current_delivery_district_id: current_delivery_district_id
        });
        wx.setStorageSync('current_delivery_man_id', current_delivery_man_id);
        wx.setStorageSync('current_delivery_name', current_delivery_name);
        wx.setStorageSync('current_delivery_district_id', current_delivery_district_id);

        this.getDeliveryStatistics();

        //this.reLoad()
    },

    async getDeliveryStatistics() {
        const that = this;
        let current_delivery_man_id = that.data.current_delivery_man_id
        let current_year = that.data.currentYear
        let current_month = that.data.currentMonth

        try {
            const res = await wx.p.request({
                url: app.globalData.API + '/delivery/index/get-delivery-statistics',
                header: {
                    'Content-Type': 'application/json',
                    "x-api-key": this.data.access_token,
                },
                method: "POST",
                data: {
                    current_delivery_man_id,
                    current_year,
                    current_month
                },
            });

            if (res.data.code === 200) {
                const history = res.data.data;
                if (history.length > 0) {
                    const result = history.reduce((acc, item) => {
                        acc[item.day] = item;
                        return acc;
                    }, {});

                    this.setData({
                        formatter: function (day) {
                            const year = day.date.getFullYear();
                            const month = String(day.date.getMonth() + 1).padStart(2, '0');
                            const date = String(day.date.getDate()).padStart(2, '0');
                            const day_key = `${year}-${month}-${date}`;
                            if (day_key in result) {
                                const day_status = result[day_key];
                                day.topInfo = `${day_status.daily_count}单`;
                                day.bottomInfo = `${day_status.deliver_fee_daily_sum}元`;
                                day.className = 'orange-brown';
                            }
                            return day;
                        },
                    });
                }
            } else if (res.data.code === 0) {
                clearUserLocalStorage();
                wx.reLaunch({
                    url: "/pages/login/login"
                });
            }
        } catch (error) {
            wx.showToast({
                title: '请求错误',
                icon: 'error',
                duration: 2000,
            });
        }
    },
});
